/**  
 * All rights Reserved, Designed By www.shatayy.com
 * @Title:  ${file_name}   
 * @Package ${package_name}   
 * @Description:    ${todo}(用一句话描述该文件做什么)   
 * @author: 宁波沙塔信息技术有限公司     
 * @date:   ${date} ${time}   
 * @version V1.0 
 * @Copyright: ${year} www.tydic.com Inc. All rights reserved. 
 * 注意：本内容仅限于宁波沙塔信息技术股份有限公司内部传阅，禁止外泄以及用于其他的商业目
 */
package com.nbst.controller.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.nbst.dao.mapper.mes.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nbst.comnutil.NormalResult;
import com.nbst.comnutil.Tools;
import com.nbst.model.base.Base;
import com.nbst.model.base.EnumLogName;
import com.nbst.model.base.Role;
import com.nbst.model.base.User;
import com.nbst.myInterface.MyLog;
import com.nbst.service.base.IDepartmentService;
import com.nbst.service.base.IMenuService;
import com.nbst.service.base.IRolePermissionService;
import com.nbst.service.base.IRolesService;
import com.nbst.service.base.IUserService;

import net.sf.json.JSONObject;

/**
 * @ClassName: RolesController
 * @Description:
 * @author 兵
 * @date 2017-8-17
 * 
 */
@RestController
@RequestMapping("/roles")
public class RolesController {
	@Autowired
	IRolesService rolesService;

	@Autowired
	IRolePermissionService rolepermissionservice;

	@Autowired
	IMenuService permissionsservice;

	@Autowired
	IUserService userroleservice;

	@Autowired
	IDepartmentService departmentservice;

	@Autowired
	UserMapper userMapper;

	/**
	 * 用户操作页面下的角色下拉列表
	 *
	 * @return Object
	 * @author King
	 * @date 2018年11月13日
	 */
	@GetMapping(value = "/userPageAccredit.action")
	public Object userPageAccredit() {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		List<Role> list = new ArrayList<Role>();
		Map<String,Object> map = new HashMap<>(8);
		if ("admin".equals(user.getAccount()) || "system".equals(user.getAccount())) {
			list = rolesService.findByCondition(map);
		} else {
			map.put("uId", user.getId());
			list = rolesService.findByUid(map);
		}
		JSONObject json = new JSONObject();
		json.put("total", list.size());
		json.put("rows", list);
		return json.toString();
	}

	/**
	 * 
	 * @Title: addNews @Description: 为角色批量添加用户 @param @param rId @param @param
	 *         ids @param @return @return NormalResult @throws
	 */
	@MyLog(value = EnumLogName.批量授权)
	@RequestMapping(value = "/roleAddNewsUser.action", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public NormalResult addNews(Integer rId, String ids) {
		return rolesService.addNews(rId, ids);
	}

	@RequestMapping(value = "/getRole2User.action", method = RequestMethod.POST)
	@ResponseBody
	public Object getRole2User(Integer rId) {
		Map<String,Object> map = new HashMap<>();
		map.put("rId", rId);
		List<Base> list = rolesService.getRole2User(map);
		List<Base> dlist = departmentservice.getDepartmentTree(map);
		for (Base base : dlist) {
			list.add(base);
		}
		return list;

	}

	/**
	 * 
	 * @Title: getUserRolesList @Description: 根据用户ID查询用户拥有的角色 @param @param
	 *         uId @param @param rId @param @return @return Object @throws
	 */
	@RequestMapping(value = "/getUserRolesList.action", method = RequestMethod.POST)
	@ResponseBody
	public Object getUserRolesList(String uId, String rId) {
		Map<String,Object> map = new HashMap<>();
		if (!StringUtils.isEmpty(rId)) {
			map.put("rId", rId);
		}
		if (!StringUtils.isEmpty(uId)) {
			map.put("uId", uId);
		}
		return rolesService.getUserRolesList(map);
	}

	/**
	 * 
	 * @Title: findByCondition @Description: 根据条件获取角色列表 @param @param record
	 *         Roles实体类 @param @param offset 分页起始行数 @param @param row
	 *         显示数据量（行） @param @return @return Object @throws
	 */
	@RequestMapping(value = "/getRolesList.action", method = RequestMethod.POST)
	@ResponseBody
	public Object findByCondition(Role record, @RequestParam(required = false, defaultValue = "1") Integer offset,
			@RequestParam(required = false, defaultValue = "1000") Integer row) {
		Map<String,Object> map = Tools.transBean2Map(record);
		Page page = PageHelper.startPage(Tools.getPageNum(offset, row), row, true);
		List<Role> list = rolesService.findByCondition(map);
		JSONObject json = new JSONObject();
		json.put("total", page.getTotal());
		List<Base> mlist = permissionsservice.getRolePermissionList(map);
		List<Base> ulist = rolesService.getRole2User(map);
		List<Base> dlist = departmentservice.getDepartmentTree(map);
		for (Base base : dlist) {
			ulist.add(base);
		}

		json.put("rows", list);
		json.put("menu", mlist);
		json.put("user", ulist);
		return json.toString();
	}

	@RequestMapping(value = "/getAllPM.action", method = RequestMethod.GET)
	@ResponseBody
	public List<String> getAllPM(){
		Map map=new HashMap();
		return userMapper.getAllPM(map);
	}

	/**
	 * 
	 * @Title: insert @Description: 新增角色信息 @param @param record
	 *         Roles实体类 @param @param session @param @return @return
	 *         NormalResult @throws
	 */
	@MyLog(EnumLogName.新增角色)
	@RequestMapping(value = "/addNew.action", method = RequestMethod.POST)
	@ResponseBody
	public NormalResult insert(Role record, String ids, HttpSession session) {
		NormalResult result = new NormalResult();
		User user = (User) session.getAttribute("user");
		if (StringUtils.isEmpty(record.getrName())) {
			result.setCode("9999");
			result.setMessage("角色名称不能为空");
			return result;
		}
		NormalResult nr = rolesService.insertSelective(record);
		if ("9999".equals(nr.getCode())) {
			return nr;
		}
		String[] id = new String[] {};
		if (!StringUtils.isEmpty(ids)) {
			id = ids.split(",");
		}
		return rolepermissionservice.roleBulkaddPermission(Integer.valueOf(nr.getId()), id);

	}

	/**
	 * 
	 * @Title: update @Description: 根据主键ID修改角色信息 @param @param record
	 *         Roles实体类 @param @param session @param @return @return
	 *         NormalResult @throws
	 */
	@MyLog(value = EnumLogName.角色授权修改)
	@RequestMapping(value = "/updateRoles.action", method = RequestMethod.POST)
	@ResponseBody
	public NormalResult update(Role record, String ids) {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		NormalResult nr = new NormalResult();
		try {
			nr = rolepermissionservice.deleteByrId(record.getrId());
			//record.setfClosed(0);
			nr = rolesService.updateByPrimaryKeySelective(record);
			if (!StringUtils.isEmpty(ids)) {
				String[] id = ids.split(",");
				for (int i = 0; i < id.length; i++) {
					Map<String,Object> map = new HashMap<>();
					map.put("rId", record.getrId());
					map.put("pId", id[i]);
					rolepermissionservice.insertSelective(map);
				}
			}
			nr.setCode("0000");
			nr.setMessage("操作成功");
		} catch (Exception e) {
			System.out.println(e);
		}
		return nr;

	}

	/**
	 * 
	 * @Title: delete @Description: 根据主键ID物理删除角色信息 @param @param
	 *         rId @param @return @return NormalResult @throws
	 */
	@MyLog(value = EnumLogName.删除角色)
	@RequestMapping(value = "/deleteRoles.action", method = RequestMethod.POST)
	@ResponseBody
	public NormalResult delete(String rId) {
		return rolesService.deleteByPrimaryKey(rId);

	}
}